package club.janna.jrpc.service.demo;

import club.janna.jrpc.rpc.RPCInvocation;
import club.janna.jrpc.serialize.Serialization;
import club.janna.jrpc.serialize.java.JavaSerialization;
import club.janna.jrpc.service.demo.service.UserService;
import club.janna.jrpc.util.ByteUtil;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

public class ClientDemo {
    public static void main(String[] args) {
        RPCInvocation rpcInvocation = new RPCInvocation();
        rpcInvocation.setTarget(UserService.class);
        rpcInvocation.setMethod("findById");
        rpcInvocation.setParameterTypes(new Class[]{Long.class});
        rpcInvocation.setArgs(new Object[]{1L});

        // 序列化
        Serialization serialization = new JavaSerialization();
        byte[] body = serialization.serialize(rpcInvocation);

        byte[] frame = new byte[body.length + 4 + 2];
        int offset = 0;

        // 协议头
        frame[offset ++] = (byte) 0xCA;
        frame[offset ++] = (byte) 0xFE;
        // 长度
        byte[] lengthBytes = ByteUtil.int2byte(body.length);
        frame[offset ++] = lengthBytes[0];
        frame[offset ++] = lengthBytes[1];
        frame[offset ++] = lengthBytes[2];
        frame[offset ++] = lengthBytes[3];
        // 数据
        for (int i = 0; i < body.length; i++) {
            frame[offset ++] = body[i];
        }

        try {
            Socket socket = new Socket("localhost", 20880);
            socket.getOutputStream().write(frame);
            socket.getOutputStream().flush();
            System.out.println("数据发送完毕");
            InputStream in = socket.getInputStream();
            byte[] buf = new byte[1024];
            int size;
            while((size = in.read(buf)) > 0) {
                System.out.println("read -> " + new String(buf, 0, size));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
